package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 以树形结构展示数据
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1. 查出所有分类
        List<CategoryEntity> entities = this.baseMapper.selectList(null);

        //2. 组装成父子的树形结构
        //2.1 找到所有的一级分类
        List<CategoryEntity> level1Menus = entities
                .stream()
                .filter(categoryEntity ->
                        categoryEntity.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(this.getChildren(menu, entities));
                    return menu;
                })
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());

        //2. 组装成父子的树形结构
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO: 2020/11/4 检查当前删除的菜单,是否被别的地方引用

        //建议逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    //[2,25,225]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = this.findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新三级分类数据
     *
     * @param category
     */
    /*
    @Caching(evict = {
            @CacheEvict(value = {"category"}, key = "'getLevel1Categorys'"),
            @CacheEvict(value = {"category"}, key = "'getCatalogJson'")
    })
    */
    @CacheEvict(value = {"category"}, allEntries = true) //失效模式
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

        // 删除缓存中的数据 失效模式
        // redis.delete
    }


    /**
     * 获取一级分类
     *
     * @return
     */
    //SpringCache只使用了普通的读锁,没有使用写锁,实时性要求不高的数据,够用了（本地读锁）
    @Cacheable(value = {"category"}, key = "#root.method.name", sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("获取一级分类方法调用");
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
        return categoryEntities;
    }

    /**
     * 获取二级分类
     *
     * @return
     */
    @Cacheable(value = {"category"}, key = "#root.methodName")
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        System.out.println("获取二级分类方法调用");

        //将数据库的多次查询变为一次,做一次全量查询
        List<CategoryEntity> categoryAllEntities = this.baseMapper.selectList(null);

        //1.查出所有1级分类
        List<CategoryEntity> level1Categorys = this.getCatsByParent_cid(categoryAllEntities, 0L);

        //2.封装数据
        Map<String, List<Catalog2Vo>> catalogJson = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1.查1级分类下的二级分类
            List<CategoryEntity> category2Entities = this.getCatsByParent_cid(categoryAllEntities, v.getCatId());
            //2.封装上面的结果
            List<Catalog2Vo> catalog2Vos = null;
            if (!CollectionUtils.isEmpty(category2Entities)) {
                catalog2Vos = category2Entities.stream().map(category2Entity -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, category2Entity.getCatId().toString(), category2Entity.getName());
                    //3.找2级分类下的三级分类,封装vo
                    List<CategoryEntity> category3Entities = this.getCatsByParent_cid(categoryAllEntities, category2Entity.getCatId());
                    if (!CollectionUtils.isEmpty(category3Entities)) {
                        List<Catalog2Vo.Catalog3Vo> catalog3Vos = category3Entities.stream().map(category3Entity -> {
                            //4.封装成指定格式
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(category2Entity.getCatId().toString(), category3Entity.getCatId().toString(), category3Entity.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(catalog3Vos);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));

        return catalogJson;
    }

    //TODO 产生堆外内存溢出: OutOfDirectMemoryError,切换为jedis
    //@Override 旧方法,没有使用SpringCache,自己写缓存,并使用Redisson
    public Map<String, List<Catalog2Vo>> getCatalogJson2() {

        /**
         * 先从缓存中查找
         * 缓存中放json字符串,String和JSONString是不一样的
         * 1.空结果缓存,解决缓存穿透
         * 2.设置过期时间,加随机值,解决缓存雪崩
         * 3.加锁,解决缓存击穿
         */
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");

        if (!StringUtils.isEmpty(catalogJSON)) {
            //缓存中有,转为指定的对象
            System.out.println("缓存命中");
            Map<String, List<Catalog2Vo>> catalogJSONFromRedis = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });
            return catalogJSONFromRedis;
        } else {
            //缓存中没有,查询数据库
            System.out.println("缓存没有命中");
            Map<String, List<Catalog2Vo>> catalogJsonFromDB = this.getCatalogJsonFromDBWithRedissonLock();
            return catalogJsonFromDB;
        }

    }


    /**
     * 本地锁
     *
     * @return
     */
    private Map<String, List<Catalog2Vo>> getCatalogJsonFromDBWithLocalLock() {

        //本地锁只锁当前进程,必须使用分布式锁
        synchronized (this) {
            //得到锁以后,我们应该再去缓存中确认
            return getDataFromDB();
        }
    }

    /**
     * Redisson
     *
     * @return
     */
    private Map<String, List<Catalog2Vo>> getCatalogJsonFromDBWithRedissonLock() {

        //1.抢占分布式锁
        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock();

        Map<String, List<Catalog2Vo>> dataFromDB;
        try {
            //执行业务
            dataFromDB = getDataFromDB();
        } finally {
            //解锁
            lock.unlock();
        }
        return dataFromDB;

    }

    /**
     * Redis锁
     *
     * @return
     */
    private Map<String, List<Catalog2Vo>> getCatalogJsonFromDBWithRedisLock() {

        //使用分布式锁,设置过期时间,用UUID标识自己的锁
        String uuid = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("获取分布式锁成功");
            Map<String, List<Catalog2Vo>> dataFromDB;
            try {
                //加锁成功,执行业务
                dataFromDB = getDataFromDB();
            } finally {
                //原子删锁
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                Long result = stringRedisTemplate.execute(
                        new DefaultRedisScript<Long>(script, Long.class),
                        Arrays.asList("lock"),
                        uuid);
            }
            return dataFromDB;

        } else {
            //加锁失败...重试 自旋
            System.out.println("获取分布式锁失败...等待重试");

            //休眠200ms重试
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return getCatalogJsonFromDBWithRedisLock();

        }


    }

    /**
     * 从数据库查询三级分类
     *
     * @return
     */
    private Map<String, List<Catalog2Vo>> getDataFromDB() {
        //排队得到锁以后,我们应该再去缓存中确认,因为可能别人先得到锁,已经完成缓存
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            //缓存中有,转为指定的对象
            Map<String, List<Catalog2Vo>> catalogJSONFromRedis = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });
            return catalogJSONFromRedis;
        }
        System.out.println("开始查询数据库" + Thread.currentThread().getName());
        /**
         * 将数据库的多次查询变为一次,做一次全量查询
         */
        List<CategoryEntity> categoryAllEntities = this.baseMapper.selectList(null);

        //1.查出所有1级分类
        List<CategoryEntity> level1Categorys = this.getCatsByParent_cid(categoryAllEntities, 0L);

        //2.封装数据
        Map<String, List<Catalog2Vo>> catalogJson = level1Categorys.stream().collect(Collectors.toMap(categoryEntity -> categoryEntity.getCatId().toString(), categoryEntity -> {
            //1.查1级分类下的二级分类
            List<CategoryEntity> category2Entities = this.getCatsByParent_cid(categoryAllEntities, categoryEntity.getCatId());
            //2.封装上面的结果
            List<Catalog2Vo> catalog2Vos = null;
            if (!CollectionUtils.isEmpty(category2Entities)) {
                catalog2Vos = category2Entities.stream().map(category2Entity -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(categoryEntity.getCatId().toString(), null, category2Entity.getCatId().toString(), category2Entity.getName());
                    //3.找2级分类下的三级分类,封装vo
                    List<CategoryEntity> category3Entities = this.getCatsByParent_cid(categoryAllEntities, category2Entity.getCatId());
                    if (!CollectionUtils.isEmpty(category3Entities)) {
                        List<Catalog2Vo.Catalog3Vo> catalog3Vos = category3Entities.stream().map(category3Entity -> {
                            //4.封装成指定格式
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(category2Entity.getCatId().toString(), category3Entity.getCatId().toString(), category3Entity.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(catalog3Vos);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));

        //3.将数据放入缓存,对象需要转为json
        String jsonString = JSON.toJSONString(catalogJson);
        stringRedisTemplate.opsForValue().set("catalogJSON", jsonString);

        return catalogJson;
    }

    /**
     * 根据父分类id查询子分类
     *
     * @param categoryEntities 范围List
     * @param parent_cid       父分类id
     * @return List
     */
    private List<CategoryEntity> getCatsByParent_cid(List<CategoryEntity> categoryEntities, Long parent_cid) {
        //return this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        List<CategoryEntity> collect = categoryEntities
                .stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == parent_cid)
                .collect(Collectors.toList());
        return collect;
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //1.收集当前节点id
        paths.add(catelogId);
        CategoryEntity entity = this.getById(catelogId);
        if (entity.getParentCid() != 0) {
            this.findParentPath(entity.getParentCid(), paths);
        }
        return paths;
    }

    //[225,25,2]
    //递归查找指定菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all
                .stream()
                .filter(categoryEntity ->
                        categoryEntity.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
                    // 1.找到子菜单
                    categoryEntity.setChildren(this.getChildren(categoryEntity, all));
                    return categoryEntity;
                })
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
        return children;
    }

}